package zblibrary.facechat.modules.mine;

import static zuo.biao.library.util.CommonUtil.toActivity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import lingxi.common.config.Api;
import lingxi.common.config.Constants;
import lingxi.common.okhttp.OkUtil;
import lingxi.common.okhttp.ResultCallback;
import lingxi.common.result.Result;
import lingxi.common.util.ContentUtil;
import lingxi.common.util.SPUtil;
import lingxi.entity.UserInfo;
import lingxi.module.main.MainActivity;
import lingxi.module.member.LoginActivity_LX;
import lingxi.module.mine.PersonalInfoActivity;
import lingxi.module.mine.RelevantActivity;
//import lingxi.module.setting.AboutActivity;
import me.cl.library.base.BaseFragment;
import okhttp3.Call;
import zblibrary.facechat.R;
import zblibrary.facechat.databinding.MineFragmentBinding;
import zblibrary.facechat.modules.SettingActivity;
import zblibrary.facechat.modules.login.LoginActivity;
import zblibrary.facechat.util.SharedPreferencesUtils;
import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.ui.AlertDialog;

/**
 * 我的界面
 */
public class MineFragment extends BaseFragment implements View.OnClickListener, AlertDialog.OnDialogButtonClickListener {

    private MineFragmentBinding mFragmentBinding;

    private ImageView mUserImg;
    private TextView mUserName;
    private TextView mMineRelevant;

    private String mUserId;
    private OperateBroadcastReceiver receiver;

    protected BaseActivity context = null;

    public static MineFragment newInstance() {
        MineFragment fragment = new MineFragment();
        return fragment;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        context = (BaseActivity) getActivity();
        mFragmentBinding = MineFragmentBinding.inflate(inflater, container, false);
        init();
        initReceiver();
        return mFragmentBinding.getRoot();
    }

    private void init() {
        mUserImg = mFragmentBinding.userImg;
        mUserName = mFragmentBinding.userName;
//        mMineRelevant = mFragmentBinding.actionRelevant;

        mFragmentBinding.userBody.setOnClickListener(this);
//        mFragmentBinding.actionReply.setOnClickListener(this);
//        mFragmentBinding.actionRelevant.setOnClickListener(this);
        mFragmentBinding.actionSetting.setOnClickListener(this);
        mFragmentBinding.actionAbout.setOnClickListener(this);
        mFragmentBinding.actionSignOut.setOnClickListener(this);

        mUserId = SPUtil.build().getString(Constants.SP_USER_ID);
        // 获取用户信息
        postUserInfo(mUserId);
    }

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (! isPositive) {
            return;
        }

        switch (requestCode) {
            case 0:
                logout();
                break;
            default:
                break;
        }
    }


    /**
     * 广播接收者
     * 用于更新用户信息
     */
    private final class OperateBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action != null) {
                if (Constants.UPDATE_USER_IMG.equals(action)) {
                    postUserInfo(mUserId);
                }
            }
        }
    }

    private void initReceiver() {
        receiver = new OperateBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.UPDATE_USER_IMG);
        requireActivity().registerReceiver(receiver, filter);
    }

    private void postUserInfo(String id) {
        OkUtil.post()
                .url(Api.userInfo)
                .addParam("id", id)
                .execute(new ResultCallback<Result<UserInfo>>() {

                    @Override
                    public void onSuccess(Result<UserInfo> response) {
                        initUser(response.getData());
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        initUser(null);
                    }
                });
    }

    private void initUser(UserInfo userInfo) {
        String username = getString(R.string.app_name);
        String avatar = "";
        if (userInfo != null) {
            username = userInfo.getUsername();
            avatar = userInfo.getAvatar();
        }
        mUserName.setText(username);
        ContentUtil.loadUserAvatar(mUserImg, avatar);
    }

    @Override
    public void onDestroy() {
        requireActivity().unregisterReceiver(receiver);
        super.onDestroy();
    }

    @Override
    public void onStart() {
        super.onStart();
//        ContentUtil.setMoreBadge(mMineRelevant);
//        if (Constants.isRead) {
//            ((MainActivity) requireActivity()).goneBadge();
//        }
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.user_body:
                gotoPersonal();
                break;
//            case R.id.action_reply:
//                gotoRelevant(Constants.REPLY_MY);
//                break;
//            case R.id.action_relevant:
//                gotoRelevant(Constants.REPLY_RELEVANT);
//                break;
            case R.id.action_setting:
                gotoSettings();
                break;
            case R.id.action_about:
                gotoAbout();
                break;
            case R.id.action_sign_out:
                showLogoutDialog();
                break;
        }
    }

    /**
     * 展示登出Dialog
     */
    private void showLogoutDialog() {
        new AlertDialog(context, "退出登录", "确定退出登录？", true, 0, this).show();
    }

    private void logout() {
        toLogin();
        toActivity(context, new Intent(context, LoginActivity.class));
        getActivity().finish();
    }

    /**
     * 返回登录界面，不消除用户和密码
     */
    public void toLogin() {
        //不用自动登录就可
        //获取SharedPreferences对象，使用自定义类的方法来获取对象
        SharedPreferencesUtils helper = new SharedPreferencesUtils(getActivity(), "setting");
        //创建记住密码和自动登录是默认不选,密码为空
        helper.putValues(new SharedPreferencesUtils.ContentValue("autoLogin", false));
    }

    /**
     * 返回登录界面，消除用户密码
     */
    public void toLogin2() {
        //置空密码即可
        //获取SharedPreferences对象，使用自定义类的方法来获取对象
        SharedPreferencesUtils helper = new SharedPreferencesUtils(getActivity(), "setting");
        //创建记住密码和自动登录是默认不选,密码为空
        helper.putValues(
                new SharedPreferencesUtils.ContentValue("remenberPassword", false),
                new SharedPreferencesUtils.ContentValue("autoLogin", false),
                new SharedPreferencesUtils.ContentValue("password", ""));
    }

    @Override
    public void onPause() {
        super.onPause();
        // 解决Activity has leaked window that was originally added here
        // 如果dialog存在或显示，dismiss
    }

    // 前往信息修改
    private void gotoPersonal() {
        Intent goPerson = new Intent(getActivity(), PersonalInfoActivity.class);
        startActivity(goPerson);
    }

    // 前往关于
    private void gotoAbout() {
        Intent goAbout = new Intent(getActivity(), AboutActivity.class);
        startActivity(goAbout);
    }

    private void gotoSettings() {
        toActivity(context, new Intent(context, SettingActivity.class));
    }

    // 前往与我相关
    private void gotoRelevant(String type) {
        Intent goRelevant = new Intent(getActivity(), RelevantActivity.class);
        goRelevant.putExtra(Constants.REPLY_TYPE, type);
        startActivity(goRelevant);
    }

    // 前往登录
    private void gotoLogin() {
        MainActivity activity = (MainActivity) getActivity();
        SPUtil.build().putBoolean(Constants.SP_BEEN_LOGIN, false);
        Intent intent = new Intent(activity, LoginActivity_LX.class);
        startActivity(intent);
        if (activity != null) {
            activity.finish();
        }
    }

}
